package com.dianxin.farm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dianxin.farm.entity.Manager;
import com.dianxin.farm.filter.AuthContext;
import com.dianxin.farm.filter.Certificate;
import com.dianxin.farm.mapper.customer.ManagerMapper;
import com.dianxin.farm.service.CurrentLoginService;
import com.dianxin.farm.util.exception.ChainException;
import com.dianxin.farm.util.web.ResultCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @auther xukai
 * @date 2020/9/28.
 */
@Service
public class CurrentLoginServiceImpl implements CurrentLoginService {


    @Resource
    private ManagerMapper managerMapper;

    @Override
    public String getToken() {
        Certificate certificate = AuthContext.get();
        if (certificate == null){
            throw new ChainException(ResultCode.USER_NOT_LOGIN);//用户状态丢失
        }
        String token=certificate.getToken();
        if (token==null || "".equals(token)){
            throw new ChainException(ResultCode.USER_NOT_LOGIN);//用户状态丢失
        }
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("token",token);
        Manager manager=managerMapper.selectOne(wrapper);
        if (manager==null){
            throw new ChainException(ResultCode.USER_NOT_LOGIN);
        }

        return certificate.getToken();

    }

    @Override
    public Manager getManager() {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("token",getToken());
        return managerMapper.selectOne(wrapper);
    }

    @Override
    public Integer getId() {
        return getManager().getId();
    }
}
